import React, { PureComponent } from 'react';
import { Upload, Button, message } from 'antd';
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
import styles from './index.less'

const DEFAULT_ACCEPT_TILE = ['.jpg', '.jpeg', '.png', '.bmp'];

export default class SelectAvatar extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            imageUrl: undefined,
            crop: {
                unit: 'px',
                x: 0,
                y: 0,
                width: 80,
                height: 80,
                aspect: 1 / 1
            }
        };
    }

    onImageLoaded = image => {
        this.imageRef = image;
    };

    onCropComplete = crop => {
        this.makeClientCrop(crop);
    };

    onCropChange = (crop, percentCrop) => {
        this.setState({ crop });
    };

    async makeClientCrop(crop) {
        if (this.imageRef && crop.width && crop.height) {
            const croppedImage = await this.getCroppedImg(
                this.imageRef,
                crop,
                'avatar.jpeg'
            );
            this.setState({ croppedImage });
        }
    }

    getCroppedImg(image, crop, fileName) {
        const canvas = document.createElement('canvas');
        const scaleX = image.naturalWidth / image.width;
        const scaleY = image.naturalHeight / image.height;
        canvas.width = crop.width;
        canvas.height = crop.height;
        const ctx = canvas.getContext('2d');

        ctx.drawImage(
            image,
            crop.x * scaleX,
            crop.y * scaleY,
            crop.width * scaleX,
            crop.height * scaleY,
            0,
            0,
            crop.width,
            crop.height
        );

        return new Promise((resolve, reject) => {
            canvas.toBlob(blob => {
                if (!blob) {
                    console.error('Canvas is empty');
                    return;
                }
                blob.name = fileName;
                window.URL.revokeObjectURL(this.fileUrl);
                this.fileUrl = window.URL.createObjectURL(blob);
                resolve(blob);
            }, 'image/jpeg');
        });
    }

    render() {
        const { crop, imageUrl } = this.state;

        const props = {
            accept: DEFAULT_ACCEPT_TILE.join(','),
            showUploadList: false,
            beforeUpload: (file) => {
                const { name } = file;
                const type = name.substring(name.lastIndexOf('.'));
                if (DEFAULT_ACCEPT_TILE.indexOf(type) !== -1) {
                    const reader = new FileReader();
                    reader.addEventListener('load', () => {
                        this.setState({ imageUrl: reader.result });
                    });
                    reader.readAsDataURL(file);
                } else {
                    message.error('不支持的文件类型', 1);
                    return false;
                }

                return false;
            }
        };

        return (
            <div className={styles.basic_wrapper}>
                <div className={styles.selected_wrapper}>
                    <div>
                        <div className={styles.tips}>
                            方法一：选择本地照片，上传编辑自己的头像
                    </div>
                        <div>
                            {imageUrl && (
                                <ReactCrop
                                    crop={this.state.crop}
                                    locked={true}
                                    imageStyle={{ maxWidth: 480, maxHeight: 270 }}
                                    ruleOfThirds
                                    src={imageUrl}
                                    onImageLoaded={this.onImageLoaded}
                                    onComplete={this.onCropComplete}
                                    onChange={this.onCropChange}
                                />
                            )}
                        </div>
                        <div className={styles.btn_wrapper} style={imageUrl ? { marginTop: 16 } : { marginBottom: 64 }}>
                            <Upload {...props}>
                                <Button >选择图片</Button>
                                <div className={styles.sub_tips}>支持jpg、jpeg、png、bmp格式的图片</div>
                            </Upload>
                        </div>
                    </div>
                    {!imageUrl &&
                        <div>
                            <div className={styles.tips}>
                                方法二：选择推荐头像，快速上传头像
                        </div>
                        </div>
                    }
                </div>
                <div className={styles.preview_wrapper}>
                    <div className={styles.tips}>
                        头像预览
                    </div>
                    {this.fileUrl &&
                        <div>
                            <img style={{ width: 100, height: 100 }} src={this.fileUrl} />
                        </div>
                    }
                </div>
            </div>
        );
    }
}
